package org.groupg.practice;

import org.jgrapht.Graph;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;

import java.util.Set;

public class GraphTraversalExample {

    public static void main(String[] args) {
        // 创建一个有向图
        Graph<String, DefaultEdge> graph = new DefaultDirectedGraph<>(DefaultEdge.class);

        // 添加顶点和边
        graph.addVertex("a");
        graph.addVertex("b");
        graph.addVertex("c");
        graph.addVertex("d");
        graph.addEdge("a", "b");
        graph.addEdge("b", "c");
        graph.addEdge("a", "c");
        graph.addEdge("c", "d");

        // 遍历每个节点及其依赖的节点
        for (String vertex : graph.vertexSet()) {


            // 获取当前节点的所有出边（即依赖的节点）
            Set<DefaultEdge> outgoingEdges = graph.outgoingEdgesOf(vertex);
            boolean first = true;
            for (DefaultEdge edge : outgoingEdges) {
                String targetVertex = graph.getEdgeTarget(edge);
                if (first) {
                    System.out.print(targetVertex);
                    first = false;
                } else {
                    System.out.print(", " + targetVertex);
                }
            }

            // 如果没有依赖的节点
            if (outgoingEdges.isEmpty()) {
                System.out.print("none");
            }
            System.out.print(" depends on " + vertex );
            System.out.println();
        }
    }
}